<template>
  <fieldset>
    <legend>二级联动</legend>
    省：
    <select v-model="sel1" @change="provinceChange(sel1)">
      <option v-for="item in province" :value="item.id" :key="item.id">
        {{ item.name }}
      </option>
    </select>
    市：
    <select v-model="sel2" @change="countyChange(sel2)">
      <option v-for="item in city" :key="item.id" :value="item.id">
        {{ item.name }}
      </option>
    </select>
    县：
    <select v-model="sel3">
      <option v-for="item in county" :key="item.id" :value="item.id">
        {{ item.name }}
      </option>
    </select>
  </fieldset>
</template>
<script>
import * as api from "@/api/select";
export default {
  data() {
    return {
      province: [],
      sel1: 1,
      sel2: "",
      sel3: "",
      city: [],
      county: [],
    };
  },
  methods: {
    provinceChange(pid) {
      api.fetchCity(pid).then((res) => {
        console.log("市：", res);
        this.city = res;
        //默认选中
        if (res.length > 0) {
          this.sel2 = res[0].id;
          this.countyChange(this.sel2);
        }
      });
    },
    countyChange(cid) {
      api.fetchCity(cid).then((res) => {
        console.log("县：", res);
        this.county = res;
        //默认选中
        if (res.length > 0) {
          this.sel3 = res[0].id;
        }
      });
    },
  },
  mounted() {
    api.fetchData().then((res) => {
      console.log("二级省：", res);
      this.province = res;
      let pid = res[0].id;
      this.provinceChange(pid);
    });
  },
};
</script>
<style scoped>
select {
  width: 100px;
}
</style>
